package com_fit.springboot_fit.service.impl;

import com_fit.springboot_fit.entity.AdminMenu;
import com_fit.springboot_fit.entity.AdminPower;
import com_fit.springboot_fit.entity.AdminUser;
import com_fit.springboot_fit.repository.AdminMenuRepository;
import com_fit.springboot_fit.repository.AdminPowerRepository;
import com_fit.springboot_fit.service.AdminMenuService;
import com_fit.springboot_fit.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminMenuServiceImpl implements AdminMenuService {

    @Autowired
    private AdminMenuRepository menuRepository;

    @Autowired
    private AdminPowerRepository powerRepository;

    @Autowired
    @Lazy
    private AdminUserService userService;

    @Override
    public List<AdminMenu> findAllShowMenu() {
        return menuRepository.findByIsShowOrderBySortAsc(AdminUser.YesNoEnum.yes);
    }

    @Override
    public List<AdminMenu> findShowMenuByPid(Integer pid) {
        return menuRepository.findByPidAndIsShowOrderBySortAsc(pid, AdminUser.YesNoEnum.yes);
    }

    @Override
    public List<AdminMenu> buildMenuTree(List<AdminMenu> menus) {
        List<AdminMenu> result = new ArrayList<>();

        // 找到所有顶级菜单 (pid=0)
        List<AdminMenu> topMenus = menus.stream()
                .filter(menu -> menu.getPid() == 0)
                .collect(Collectors.toList());

        // 为每个顶级菜单设置子菜单
        for (AdminMenu topMenu : topMenus) {
            buildChildren(topMenu, menus);
            result.add(topMenu);
        }

        return result;
    }

    // 递归构建子菜单
    private void buildChildren(AdminMenu parentMenu, List<AdminMenu> allMenus) {
        List<AdminMenu> children = allMenus.stream()
                .filter(menu -> menu.getPid().equals(parentMenu.getId()))
                .collect(Collectors.toList());

        if (!children.isEmpty()) {
            parentMenu.setChildren(children);
            for (AdminMenu child : children) {
                buildChildren(child, allMenus);
            }
        }
    }

    @Override
    public List<AdminMenu> getMenusByUserId(Integer userId) {
        // 获取用户信息
        AdminUser user = userService.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 如果是超级管理员，拥有所有权限
        if (AdminUser.YesNoEnum.yes.equals(user.getIsAdmin())) {
            List<AdminMenu> allMenus = findAllShowMenu();
            return buildMenuTree(allMenus);
        }

        // 不是超级管理员，根据权限表获取有权限的菜单ID
        List<AdminPower> userPowers = powerRepository.findByUid(userId);
        List<AdminPower> groupPowers = powerRepository.findByGid(user.getGid());

        List<Integer> menuIds = new ArrayList<>();

        // 添加用户自身的权限
        if (userPowers != null && !userPowers.isEmpty()) {
            menuIds.addAll(userPowers.stream()
                    .map(AdminPower::getMid)
                    .collect(Collectors.toList()));
        }

        // 添加用户组的权限
        if (groupPowers != null && !groupPowers.isEmpty()) {
            menuIds.addAll(groupPowers.stream()
                    .map(AdminPower::getMid)
                    .collect(Collectors.toList()));
        }

        // 去重
        menuIds = menuIds.stream().distinct().collect(Collectors.toList());

        // 获取这些菜单ID对应的菜单
        List<AdminMenu>有权限的菜单 = new ArrayList<>();
        for (Integer menuId : menuIds) {
            menuRepository.findById(menuId).ifPresent(有权限的菜单::add);
        }

        // 构建菜单树
        return buildMenuTree(有权限的菜单);
    }

    @Override
    public boolean checkMenuPermission(Integer userId, String m, String c, String a) {
        // 获取用户信息
        AdminUser user = userService.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 超级管理员拥有所有权限
        if (AdminUser.YesNoEnum.yes.equals(user.getIsAdmin())) {
            return true;
        }

        // 查找对应的菜单
        AdminMenu menu = menuRepository.findByMAndCAndA(m, c, a);
        if (menu == null) {
            // 菜单不存在，默认不允许访问
            return false;
        }

        // 检查用户是否有该菜单的权限
        AdminPower userPower = powerRepository.findByUidAndMid(userId, menu.getId());
        if (userPower != null) {
            return true;
        }

        // 检查用户组是否有该菜单的权限
        AdminPower groupPower = powerRepository.findByGidAndMid(user.getGid(), menu.getId());
        return groupPower != null;
    }
}
